import 'package:flutter/material.dart';

class ProgressDialog extends StatefulWidget {
  //子布局
  final Widget child;

  //加载中是否显示
  bool loading;

  //进度提醒内容
  final String msg;

  //加载中动画
  final Widget progress;

  //背景透明度
  final double alpha;

  //字体颜色
  final Color textColor;

  ProgressDialog(
      {Key key,
      @required this.loading,
      this.msg,
      this.progress = const CircularProgressIndicator(
        valueColor: AlwaysStoppedAnimation(Colors.white),
      ),
      this.alpha = 0.6,
      this.textColor = Colors.white,
      @required this.child})
      : assert(child != null),
        assert(loading != null),
        super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _ProgressDialog();
  }
}

class _ProgressDialog extends State<ProgressDialog> {
  @override
  Widget build(BuildContext context) {
    List<Widget> widgetList = [];
    widgetList.add(widget.child);
    if (widget.loading) {
      Widget layoutProgress;
      if (widget.msg == null) {
        layoutProgress = Center(
          child: widget.progress,
        );
      } else {
        layoutProgress = Center(
          child: Container(
            padding: const EdgeInsets.all(20.0),
            decoration: BoxDecoration(
                color: Colors.black87,
                borderRadius: BorderRadius.circular(4.0)),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                widget.progress,
                Container(
                  padding: const EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 0),
                  child: Text(
                    widget.msg,
                    style: TextStyle(color: widget.textColor, fontSize: 16.0),
                  ),
                )
              ],
            ),
          ),
        );
      }
      widgetList.add(Opacity(
        opacity: widget.alpha,
        child: new ModalBarrier(color: Colors.black87),
      ));
      widgetList.add(layoutProgress);
    }
    return WillPopScope(
        child: Stack(
          children: widgetList,
        ),
        // ignore: missing_return
        onWillPop: () {
          if (widget.loading) {
            setState(() {
              widget.loading = false;
            });
          } else {
            Navigator.of(context).pop();
          }
        });
  }
}
